/* eslint-disable camelcase */
import {
  userCollection
} from '../utils/config'
import platformApi from '../../platforms/index'

/**
 * Apple登录
 * @param {String} nickName   // 用户自定义昵称，若无，则为fullName拼接，若fullName无，则为email
 * @param {String} fullName   // 用户自定义名称
 * @param {String} email   // 用户邮箱，如果有则是私密邮箱，发邮件需通过Apple的服务器
 * @param {String} authorizationCode   // 用户标识码
 * @param {String} identityToken   // 身份令牌是JSON Web令牌（JWT），用于账户验证解析
 * @param {Number} realUserStatus   // 真实用户状态，0 Unsupported  1 Unknown  2  LikelyReal 真人
 */
export default async function loginByApple ({
  nickName,
  fullName,
  email,
  authorizationCode,
  identityToken,
  realUserStatus,
  inviteCode,
  myInviteCode,
  type,
  needPermission,
  platform,
  role
}) {
  const config = this._getConfig()

  const appleConfig = config && config['app-plus'] && config['app-plus'].oauth && config['app-plus'].oauth.apple

  // univerifyConfig配置错误处理
  if (!appleConfig) {
    throw new Error('请在config.json或init方法中，app-plus.oauth.apple 下配置相关参数')
  }

  const { bundleId } = appleConfig
  if (!bundleId) {
    throw new Error('请在config.json或init方法中 app-plus.oauth.apple 下配置bundleId')
  }

  if (!identityToken) {
    throw new Error('[loginByApple] 苹果登录需要传递identityToken')
  }

  const clientPlatform = platform || this.context.PLATFORM
  fullName = nickName || (fullName && Object.keys(fullName).length > 0 ? fullName.familyName + fullName.givenName : '')

  const { code, msg } = await platformApi.initApple({
    clientType: clientPlatform
  }).verifyIdentityToken(identityToken)

  if (code !== 0) {
    return {
      code,
      msg
    }
  }

  const {
    iss,
    sub,
    aud,
    email: checkEmail
  } = msg

  // 签名都是苹果签发的，因此此项应恒为 https://appleid.apple.com
  if (iss !== 'https://appleid.apple.com') {
    return {
      code: 10706,
      msg: '签发机构检验失败'
    }
  }

  if (!sub) {
    return {
      code: 10701,
      msg: '获取用户唯一标识符失败'
    }
  }

  if (bundleId !== aud) {
    return {
      code: 10702,
      msg: 'bundleId校验失败，请确认配置后重试'
    }
  }

  const nickname = fullName || `新用户${checkEmail.split('@')[0]}`
  const userList = await userCollection.where({
    apple_openid: sub
  }).get()
  // openId 已注册
  if (userList && userList.data && userList.data.length > 0) {
    if (type === 'register') {
      return {
        code: 10703,
        msg: '此账户已注册'
      }
    }

    const userMatched = userList.data[0]

    const loginExecRes = await this._loginExec(userMatched, {
      needPermission
    })

    if (loginExecRes.code !== 0) {
      return loginExecRes
    }

    return {
      ...loginExecRes,
      openid: sub
    }
  }

  /**
     * 以下为注册
     */
  if (type === 'login') {
    return {
      code: 10704,
      msg: '此账户尚未注册'
    }
  }

  const user = {
    nickname,
    apple_openid: sub,
    my_invite_code: myInviteCode,
    role
  }

  const registerExecResult = await this._registerExec(user, {
    needPermission
  })
  if (registerExecResult.code !== 0) {
    return registerExecResult
  }
  return {
    ...registerExecResult,
    openid: sub
  }
}
